package com.maikobi.maikobi.config;

import com.maikobi.maikobi.constant.BiMqConstant;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;


/**
 * BI异步图表生成消息队列配置，使用普通队列 + 死信队列实现延迟及失败重试
 * @author: Maiko7
 * @create: 2025-07-17 13:27
 */
@Configuration
public class BiMqConfig {

    // 普通交换机
    @Bean("biExchange")
    public DirectExchange biExchange() {
        return new DirectExchange(BiMqConstant.BI_EXCHANGE_NAME);
    }

    // 普通队列，设置死信交换机，设置消息TTL
    @Bean("biQueue")
    public Queue biQueue() {
        Map<String, Object> args = new HashMap<>();
        args.put("x-dead-letter-exchange", BiMqConstant.BI_DEAD_EXCHANGE_NAME);
        args.put("x-dead-letter-routing-key", BiMqConstant.BI_DEAD_ROUTING_KEY);
        args.put("x-message-ttl", BiMqConstant.BI_MESSAGE_TTL);
        return QueueBuilder.durable(BiMqConstant.BI_QUEUE_NAME).withArguments(args).build();

    }

    // 死信交换机
    @Bean("biDeadExchange")
    public DirectExchange biDeadExchange() {
        return new DirectExchange(BiMqConstant.BI_DEAD_EXCHANGE_NAME);
    }

    // 死信队列，存放失败或者超时的消息，用于补偿处理或报警
    @Bean("biDeadQueue")
    public Queue biDeadQueue() {
        return QueueBuilder.durable(BiMqConstant.BI_DEAD_QUEUE_NAME).build();
    }

    // 普通队列绑定交换机和路由键
    @Bean
    public Binding bindingBiQueue(@Qualifier("biQueue") Queue queue,
                                  @Qualifier("biExchange") DirectExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(BiMqConstant.BI_ROUTING_KEY);
    }
    // 死信队列绑定死信交换机和路由键
    @Bean
    public Binding bindingBiDeadQueue(@Qualifier("biDeadQueue") Queue queue, @Qualifier("biDeadExchange") DirectExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(BiMqConstant.BI_DEAD_ROUTING_KEY);
    }
    // 死信队列绑定交换机和路由键
    @Bean
    public Binding bindingDeadQueue(@Qualifier("biDeadQueue") Queue queue, @Qualifier("biExchange") DirectExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(BiMqConstant.BI_DEAD_ROUTING_KEY);
    }
}
